package edu.ubb.remeye.encodings.encoders.png;

import java.awt.Image;
import java.io.ByteArrayInputStream;
import java.io.IOException;

import javax.imageio.ImageIO;

import edu.ubb.remeye.encodings.encoders.ImageDecoder;
import edu.ubb.remeye.exception.ImageDecodingException;
import edu.ubb.remeye.gui.internationalization.LanguageManager;

/**
 * PNG format image decoder.
 * 
 * @author Andrew Ianicicau
 *
 */
public class PNGImageDecoder implements ImageDecoder {

	///////////////////////////////////////////////////////////////////////////////////
	////		METHODS - PNGImageDecoder
	///////////////////////////////////////////////////////////////////////////////////

	@Override
	public Image decode(byte[] encodedImage) throws ImageDecodingException {
		Image decodedImage = null;
		try {
			decodedImage = readImage(encodedImage);
		} catch (IOException e) {
			String errorMessage = "PNG " + LanguageManager.getLanguageManager().getText("decodefailed");
			throw new ImageDecodingException(errorMessage);
		}
		return decodedImage;
	}
	
	/**
	 * Returns a buffered image built from a byte array.
	 * @param imageBytes Byte array.
	 * @return Buffered image.
	 * @throws IOException
	 */
	private Image readImage(byte[] imageBytes) throws IOException {
        ByteArrayInputStream bais = new ByteArrayInputStream(imageBytes);
        return ImageIO.read(bais);
    }

}
